package cn.com.guage.dtm.utils;

import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class AESDecrypt {
	private Logger log = LoggerFactory.getLogger(getClass());
	
	//算法名称
	private final String KEY_ALGORITHM = "AES";
	
	//加解密算法/模式/填充方式
	private final String TRANSFORMATION = "AES/CBC/PKCS5Padding";
	
	private final String ALGORITHM = "SHA1PRNG";
	
	private final String CHARSET_NAME = "UTF-8";

	private Cipher cipherDecrypt;
	
	private String ivStr="0123456789ABCDEF";
	
	public AESDecrypt() {
		
	}
	
	public AESDecrypt( String keyStr) {
		
		try {
			KeyGenerator keyGenerator = KeyGenerator.getInstance( KEY_ALGORITHM );
			SecureRandom secureRandom = SecureRandom.getInstance( ALGORITHM );
	        secureRandom.setSeed(keyStr.getBytes());
	            
	        keyGenerator.init(128, secureRandom);
	        
	        SecretKey key=keyGenerator.generateKey();
	        cipherDecrypt=Cipher.getInstance( TRANSFORMATION );
	        cipherDecrypt.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(ivStr.getBytes()));
	        
		} catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | InvalidAlgorithmParameterException e) {
			log.error("初始化AES失败", e);
		}
	}


	/**
	 * 解密
	 * @param content
	 * @return
	 */
    public String decryptForCBC( String content ) {
          
        try {
            byte[] result=cipherDecrypt.doFinal( hexStr2Bytes( content ) );

            return new String(result, CHARSET_NAME);
        }catch ( Exception e ) {
        	log.error("解密失败。", e);
        }
        return null;
    }
    
    /**
	 * 解密
	 * @param content
	 * @param keyBytes
	 * @param iv
	 * @return
	 */
    public String decryptForCBC( String content, byte[] keyBytes, byte[] iv) {
          
        try {
        	KeyGenerator keyGenerator = KeyGenerator.getInstance( KEY_ALGORITHM );
        	SecureRandom secureRandom = SecureRandom.getInstance( ALGORITHM );
	        secureRandom.setSeed(keyBytes);
	            
	        keyGenerator.init(128, secureRandom);
	        
        	SecretKey key=keyGenerator.generateKey();
        	Cipher cipher=Cipher.getInstance( TRANSFORMATION );
        	cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(iv));
        
            byte[] result=cipher.doFinal( hexStr2Bytes( content ) );

            return new String(result, CHARSET_NAME);
        }catch ( Exception e ) {
        	log.error("解密失败。", e);
        }
        return null;
    }
    
    
    private byte[] hexStr2Bytes(String src){  
        int iLen=src.length()/2; //计算长度  
        byte[] ret = new byte[iLen]; //分配存储空间  
        
        char[] srcObjs = src.toCharArray();
        char[] dest = new char[2];
        
        for (int i = 0; i < iLen; i++){
            
            System.arraycopy(srcObjs, i*2, dest, 0, 2);

			ret[i] = (byte)(Integer.decode("0X"+ dest[0] + dest[1] ) & 0xFF);
        }
        return ret;
    }

}
